#!/bin/bash
# This script patches all service commands into the appropriate s6- commands
# pi-hole upstream scripts need a 'service' interface. why not systemd? docker said so.

start() {
  restart
}

stop() {
  /command/s6-svc -wD -d -T2500 /run/service/"$service"
}

restart() {
  local pid

  # Get the PID(s) of the service we are asking to restart
  mapfile -t pids < <(pgrep "$service")

  # Only attempt to stop the service if it is already running
  if [ "${#pids[@]}" -gt 0 ]; then
    stop

    for pid in "${pids[@]}"; do
      # Loop until we are certain that the process has been stopped
      while test -d /proc/"$pid"; do
        sleep 0.2
      done
    done
  fi

  # Check it hasn't been started by something else in the meantime
  pid=$(pgrep "$service")

  # Only attempt to start the service if it is not already running
  if [ -z "$pid" ]; then
    /command/s6-svc -wu -u -T2500 /run/service/"$service"
  fi

}

status() {
  /command/s6-svstat /run/service/"$service"
}

service="$1"
command="$2"

if [[ ! -d "/run/service/$service" ]] ; then
  echo "s6 service not found for $service, exiting..."
  exit
fi;

${command} "${service}"
